﻿using ByteSite.Common;
using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ByteSite.Quartz
{
    public class HttpResultfulJob : NewIJob
    {
        public override void Run(IJobExecutionContext context, ref string result)
        {
            result = string.Empty;
            Entitys.QuartzTask taskOptions = context.GetTaskOptions();
            string httpMessage = "";
            if (taskOptions == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(taskOptions.url) || taskOptions.url == "/")
            {
                return;
            }

            try
            {
                Dictionary<string, string> header = new Dictionary<string, string>();
                if (!string.IsNullOrEmpty(taskOptions.request_header))
                {
                    header = Utils.UrlParamsToDic(taskOptions.request_header);
                }

                Dictionary<string, string> parms = new Dictionary<string, string>();
                if (!string.IsNullOrEmpty(taskOptions.request_params))
                {
                    parms = Utils.UrlParamsToDic(taskOptions.request_params);
                }

                httpMessage = HttpManager.HttpSendAsync(
                    taskOptions.request_type?.ToLower() == "get" ? HttpMethod.Get : HttpMethod.Post,
                    taskOptions.url,
                    header,
                    parms);
                result = httpMessage;
            }
            catch (Exception ex)
            {
                result = ex.ToString();
                httpMessage = ex.Message;
            }

        }
    }
}